<?php
namespace app\api\controller;

use app\api\controller\Base;

/**
 * 功能说明:用户类
 * Company:物联网应用专家---成都亿佰特电子科技有限公司
 * User: 郑文军
 * Time: 2021-09-30 10:49
 * version：1.0
 */
class User extends Base
{

    public function _initialize()
    {
        parent::_initialize();
    }


    public function register()
    {
        if (request()->isPost()) {
            $param = request()->param();
            if (empty($param)) {
                err("", "账号密码有误");
            }
            if (empty($param['username']) or empty($param['password'])) {
                err("", "账号密码有误");
            }

            //查询用户名是否注册
            $exist = db('user')->where(['username' => $param['username']])->find();
            if ($exist) {
                err("", "用户名已存在");
            }

            //开始注册
            $date['username'] = $param['username'];
            $date['password'] = md5($param['password']);
            $date['create_time'] = time();


            $res = db("user")->insert($date);
            $res ? suc("", "注册成功") : err("", "注册失败");
        }
    }

    /**
     * 功能说明
     * author 郑
     * time 2021-09-30 9:41
     */
    public function login()
    {
        if (request()->isPost()) {

            $param = request()->param();

            if (empty($param)) {
                err("", "账号与密码不匹配");
            }
            if (empty($param['username']) or empty($param['password'])) {
                err("", "账号与密码不匹配");
            }

            $result = db('user')->where(['username' => $param['username']])->find();

            // 查找不到
            if (!$result) {
                err('', '账号与密码不匹配');
            }

            if ($result['status'] != 1) {
                err('', '账号已禁用，请联系管理员');
            }
            // 密码不正确
            if (md5($param['password']) != $result['password']) {
                err('', '账号与密码不匹配');
            }
            $mstr = accessEncrypt(0, $result['id'], $this->timeStamp, $result['id'], $this->accessKey);

            suc($mstr, "登录成功");
        } else {
            err("", "登录失败");
        }
        err("", "登录失败");
    }

    /**
     * 功能说明 获取用户相关信息
     * author 郑
     * time 2021-09-30 14:02
     */
    public function userinfo()
    {
        $user = db("user")->field("id,username")->where(['id' => $this->accessData['uid']])->find();
        $user['avatar'] = "https://cloudadmin.ebyte.com/uploads/avatar.png";
        $user['roles'] = 'admin';
        $user['permission'] = [
            'sys_crud_btn_add',
            'sys_crud_btn_export',
            'sys_menu_btn_add',
            'sys_menu_btn_edit',
            'sys_menu_btn_del',
            'sys_role_btn1',
            'sys_role_btn2',
            'sys_role_btn3',
            'sys_role_btn4',
            'sys_role_btn5',
            'sys_role_btn6',
        ];
        suc($user);
    }
}